<template>
  <div class="app-container">
    <div class="header">
      <el-page-header @back="goBack" :content="mode === 'edit' ? '修改队伍' : '创建队伍'" />
    </div>

    <div class="content-wrapper">
      <!-- 左侧学生列表 (3/4) -->
      <div class="left-panel">
        <student-list-panel ref="studentListPanelRef" :group-id="groupId" :group-info="groupInfo" :selected-students="selectedStudents" @select-student="handleSelectStudent" @unselect-student="handleUnselectStudent" @view-student="handleViewStudent" />
      </div>

      <!-- 右侧队伍表单 (1/4) -->
      <div class="right-panel">
        <team-form-panel ref="teamFormPanelRef" :selected-students="selectedStudents" :teacher-list="teacherList" :teacher-loading="teacherLoading" :group-info="groupInfo" :group-id="groupId" :dept-id="deptId" :grade-id="gradeId" :submitting="submitting" :is-edit="mode === 'edit'" @unselect-student="handleUnselectStudent" @submit="handleSubmit" />
      </div>
    </div>

    <!-- 学生详情弹窗 -->
    <student-detail-dialog ref="studentDetailDialogRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getGroupTeachers, getGroup } from '@/api/group'
import { addTeam, getTeam, updateTeam } from '@/api/team'
import StudentListPanel from './components/StudentListPanel.vue'
import TeamFormPanel from './components/TeamFormPanel.vue'
import StudentDetailDialog from './components/StudentDetailDialog.vue'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 从路由获取参数
const teamId = ref(route.query.teamId)
const groupId = ref(route.query.groupId)
const deptId = ref(route.query.deptId)
const gradeId = ref(route.query.gradeId)
const mode = ref(route.query.mode || 'create') // create/edit

// 分组信息
const groupInfo = ref({
  groupName: '',
  teamMax: 0,
  teacherMax: 0
})

// 已选学生
const selectedStudents = ref([])

// 教师列表
const teacherLoading = ref(false)
const teacherList = ref([])

// 提交状态
const submitting = ref(false)

// 组件引用
const studentListPanelRef = ref(null)
const teamFormPanelRef = ref(null)
const studentDetailDialogRef = ref(null)

// 获取分组详情
const getGroupInfo = async () => {
  if (!groupId.value) return

  try {
    const res = await getGroup(groupId.value)
    if (res && res.data) {
      groupInfo.value = {
        groupName: res.data.groupName || '',
        teamMax: res.data.teamMax || 0,
        teacherMax: res.data.teacherMax || 0
      }
    }
  } catch (error) {
    console.error('获取分组详情失败:', error)
    proxy.$modal.msgError('获取分组详情失败')
  }
}

// 获取队伍详情（编辑模式）
const getTeamInfo = async () => {
  if (!teamId.value || mode.value === 'create') return

  try {
    const res = await getTeam(teamId.value)
    if (res && res.data) {
      const teamData = res.data

      // 设置已选学生
      selectedStudents.value = teamData.studentTeams?.map(st => ({
        studentId: st.student.studentId,
        user: st.student.user,
        stuId: st.student.stuId,
        email: st.student.email,
        studentTeam: { teamId: st.teamId }
      })) || []

      // 如果没有 groupId，从队伍数据中获取
      if (!groupId.value) {
        groupId.value = teamData.groupId
        deptId.value = teamData.group?.deptId
        gradeId.value = teamData.group?.gradeId
      }

      // 填充表单数据
      if (teamFormPanelRef.value) {
        await teamFormPanelRef.value.fillFormData({
          teamName: teamData.teamName,
          summary: teamData.summary,
          teamLink: teamData.teamLink,
          teacherVolunteers: teamData.teamTeachers
            ?.sort((a, b) => a.sort - b.sort)
            ?.map(tt => tt.teacherId) || [],
          leaderId: teamData.studentTeams?.find(st => st.isLeader === '1')?.studentId
        })
      }
    }
  } catch (error) {
    console.error('获取队伍详情失败:', error)
    proxy.$modal.msgError('获取队伍详情失败')
  }
}

// 获取教师列表
const getTeacherList = async () => {
  if (!groupId.value) return

  teacherLoading.value = true
  try {
    const res = await getGroupTeachers(groupId.value)
    if (res && res.data) {
      teacherList.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
    teacherList.value = []
  } finally {
    teacherLoading.value = false
  }
}

// 选择学生
const handleSelectStudent = (student) => {
  if (student.studentTeam !== null) {
    proxy.$modal.msgWarning('该学生已组队，无法选择')
    return
  }

  // 检查是否超过队伍人数上限
  const teamMax = groupInfo.value.teamMax || 0
  if (teamMax > 0 && selectedStudents.value.length >= teamMax) {
    proxy.$modal.msgWarning(`队伍人数不能超过 ${teamMax} 人`)
    return
  }

  if (!selectedStudents.value.some((s) => s.studentId === student.studentId)) {
    selectedStudents.value.push(student)
  }
}

// 取消选择学生
const handleUnselectStudent = (studentId) => {
  const index = selectedStudents.value.findIndex((s) => s.studentId === studentId)
  if (index !== -1) {
    selectedStudents.value.splice(index, 1)
  }
}

// 查看学生详情
const handleViewStudent = (row) => {
  if (!studentDetailDialogRef.value) {
    console.warn('学生详情弹窗组件未加载')
    return
  }
  studentDetailDialogRef.value.openDialog(row)
}

// 提交表单
const handleSubmit = async (payload) => {
  if (submitting.value) return
  submitting.value = true

  try {
    if (mode.value === 'edit' && teamId.value) {
      // 编辑模式：更新队伍
      const updatePayload = {
        ...payload,
        teamId: teamId.value
      }
      await updateTeam(updatePayload)
      proxy.$modal.msgSuccess('修改队伍成功')
    } else {
      // 创建模式：创建新队伍
      await addTeam(payload)
      proxy.$modal.msgSuccess('创建队伍成功')
    }

    // 重置表单和数据
    resetFormAndData()

    // 刷新学生列表（因为刚创建的学生状态会变为"已组队"）
    await studentListPanelRef.value?.refresh()
  } catch (error) {
    console.error(`${mode.value === 'edit' ? '修改' : '创建'}队伍失败:`, error)
    if (error.message) {
      proxy.$modal.msgError(error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单和数据
const resetFormAndData = () => {
  // 重置右侧表单
  teamFormPanelRef.value?.resetForm()

  // 清空已选学生
  selectedStudents.value = []
}

// 返回
const goBack = () => {
  router.back()
}

// 初始化
onMounted(async () => {
  if (mode.value === 'edit' && !teamId.value) {
    proxy.$modal.msgError('缺少队伍信息，请重新选择')
    router.push('/team')
    return
  }

  if (mode.value === 'create' && !groupId.value) {
    proxy.$modal.msgError('缺少分组信息，请重新选择')
    router.push('/team')
    return
  }

  try {
    // 先获取分组详情
    await getGroupInfo()

    // 编辑模式：获取队伍详情并填充数据
    if (mode.value === 'edit') {
      await getTeamInfo()
    }

    // 最后获取教师列表
    getTeacherList()
  } catch (error) {
    console.error('页面初始化失败:', error)
    proxy.$modal.msgError('页面初始化失败')
    router.push('/team')
  }
})
</script>

<style scoped>
.header {
  margin-bottom: 20px;
}

.content-wrapper {
  display: flex;
  height: calc(100dvh - 164px);
  width: 100%;
  gap: 20px;
  align-items: flex-start;
}

.left-panel {
  width: 75%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-panel {
  width: 25%;
  height: 100%;
}
</style>
